home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / SNIP0492.ARJ / WB_FCOPY.C < prev    next >
C/C++ Source or Header  |  1990-11-01  |  2KB  |  72 lines

  1. /* 
  2. ** by: Walter Bright via Usenet C newsgroup
  3. **
  4. ** modified by: Bob Stout based on a recommendation by Ray Gardner
  5. **
  6. ** There is no point in going to asm to get high speed file copies. Since it
  7. ** is inherently disk-bound, there is no sense (unless tiny code size is
  8. ** the goal). Here's a C version that you'll find is as fast as any asm code
  9. ** for files larger than a few bytes (the trick is to use large disk buffers):
  10. */
  11.  
  12.  
  13. #if Afilecopy
  14. int file_copy(from,to)
  15. #else
  16. int file_append(from,to)
  17. #endif
  18. char *from,*to;
  19. {       int fdfrom,fdto;
  20.         int bufsiz;
  21.  
  22.         fdfrom = open(from,O_RDONLY,0);
  23.         if (fdfrom < 0)
  24.                 return 1;
  25. #if Afileappe
  26.         /* Open R/W by owner, R by everyone else        */
  27.         fdto = open(to,O_WRONLY,0644);
  28.         if (fdto < 0)
  29.         {   fdto = creat(to,0);
  30.             if (fdto < 0)
  31.                 goto err;
  32.         }
  33.         else
  34.             if (lseek(fdto,0L,SEEK_END) == -1)  /* to end of file       */
  35.                 goto err2;
  36. #else
  37.         fdto = creat(to,0);
  38.         if (fdto < 0)
  39.             goto err;
  40. #endif
  41.  
  42.         /* Use the largest buffer we can get    */
  43.         for (bufsiz = 0x4000; bufsiz >= 128; bufsiz >>= 1)
  44.         {   register char *buffer;
  45.  
  46.             buffer = (char *) malloc(bufsiz);
  47.             if (buffer)
  48.             {   while (1)
  49.                 {   register int n;
  50.  
  51.                     n = read(fdfrom,buffer,bufsiz);
  52.                     if (n == -1)                /* if error             */
  53.                         break;
  54.                     if (n == 0)                 /* if end of file       */
  55.                     {   free(buffer);
  56.                         close(fdto);
  57.                         close(fdfrom);
  58.                         return 0;               /* success              */
  59.                     }
  60.                     if (n != write(fdto,buffer,(unsigned) n))
  61.                         break;
  62.                 }
  63.                 free(buffer);
  64.                 break;
  65.             }
  66.         }
  67. err2:   close(fdto);
  68.         remove(to);                             /* delete any partial file */
  69. err:    close(fdfrom);
  70.         return 1;
  71. }
  72.